<!--
 * @Description: 测试地图组件
 * @Author: ZhangHan
 * @Date: 2025-08-14 17:14:04
 * @LastEditTime: 2025-09-15 17:37:46
 * @LastEditors: ZhangHan
-->

<template>
  <view class="container">
    <map
      id="map"
      style="width: 100%; height: 80vh"
      :latitude="center.latitude"
      :longitude="center.longitude"
      :polygons="polygons"
      :markers="markers"
      @tap="handleMapTap"
      :show-location="true"
      :enable-zoom="true"
      :enable-scroll="true"
    ></map>
    
    <view class="info-box" v-if="selectedPoint">
      <text>已选位置:</text>
      <text>纬度: {{selectedPoint.latitude.toFixed(6)}}</text>
      <text>经度: {{selectedPoint.longitude.toFixed(6)}}</text>
      <text v-if="!isInZhengzhou" class="error">当前位置不在郑州范围内!</text>
    </view>
  </view>
</template>

<script setup>
import { IMG_ALL } from '@/concacts/imgPath'
import { ref } from 'vue'

// 郑州市大致边界坐标（简化多边形）
const zhengzhouPolygon = [
  {latitude: 34.936, longitude: 112.842}, // 西北角
  {latitude: 34.936, longitude: 114.023}, // 东北角
  {latitude: 34.524, longitude: 114.023}, // 东南角
  {latitude: 34.524, longitude: 112.842}, // 西南角
  {latitude: 34.936, longitude: 112.842}  // 闭合多边形
]

// 计算郑州市中心点（大致为二七塔位置）
const center = ref({
  latitude: 34.747,
  longitude: 113.625
})

// 地图多边形配置
const polygons = ref([{
  points: zhengzhouPolygon,
  strokeWidth: 2,
  strokeColor: "#1E90FF",
  fillColor: "#1E90FF22"  // 半透明蓝色
}])

// 标记点
const markers = ref([])
const selectedPoint = ref(null)
const isInZhengzhou = ref(false)

// 判断点是否在多边形内（射线法）
function isPointInPolygon(point, polygon) {
  const x = point.longitude, y = point.latitude
  let inside = false
  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    const xi = polygon[i].longitude, yi = polygon[i].latitude
    const xj = polygon[j].longitude, yj = polygon[j].latitude
    
    const intersect = ((yi > y) !== (yj > y)) &&
      (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
    if (intersect) inside = !inside
  }
  return inside
}

// 处理地图点击
const handleMapTap = (e) => {
  const { latitude, longitude } = e.detail
  selectedPoint.value = { latitude, longitude }
  
  isInZhengzhou.value = isPointInPolygon(
    {latitude, longitude}, 
    zhengzhouPolygon
  )
  
  if (isInZhengzhou.value) {
    // 在郑州范围内，添加标记
    markers.value = [{
      id: 1,
      latitude,
      longitude,
      iconPath: IMG_ALL.LOCATION,
      width: 30,
      height: 30,
      title: "选择的位置"
    }]
  } else {
    // 不在郑州范围内，显示错误
    markers.value = []
    uni.showToast({
      title: "请选择郑州市范围内的位置",
      icon: "none",
      duration: 2000
    })
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
}

.info-box {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}

.info-box text {
  display: block;
  margin: 10rpx 0;
  font-size: 28rpx;
}

.error {
  color: #ff0000;
  font-weight: bold;
}
</style>